<template>
  <a-card>
    <h3>雇员管理</h3>
    <a-divider />

    <!-- tabs -->
    <div class="radioGroup_div dsp_flex">
      <span style="margin-right: 10px;">状态: </span>
      <div>
        <a-radio-group v-model="radioValue" @change="radioOnChange">
          <a-radio-button v-for=" item in employeeManagementTabArr" :value="item.id" :key="item.id">
            {{item.tab}}
          </a-radio-button>
        </a-radio-group>
      </div>
    </div>

    <!-- 搜索框 -->
    <div>
      <a-row>
        <a-col :span="defaultSpan">
          <a-input-group :model="searchForm" ref="searchForm">
            <a-row :gutter="8">
              <a-col :span="defaultSpanItem">
                <a-input allow-clear placeholder="请输入姓名/手机号/部门" v-model="searchForm.nameTeldepartmentVal" />
              </a-col>
              <a-col :span="defaultSpanItem">
                <a-select show-search allowClear placeholder="请选择项目名称" option-filter-prop="children" style="width: 220px" :filter-option="filterOption" @focus="handleFocus" @blur="handleBlur" @change="handleChange1">
                  <a-select-option v-for="(item,index) in selectData" :key="index" :value="item.id">
                    {{item.name}}
                  </a-select-option>
                </a-select>
              </a-col>

              <a-col :span="12" v-if="radioCurrentIdx == 'g'">
                <a-row :gutter="8">
                  <a-col :span="8">
                    <a-select show-search allowClear placeholder="请选择类型" option-filter-prop="children" style="width: 220px" :filter-option="filterOption" @change="UnusualHandleChange">
                      <a-select-option v-for="(item, index) in typeSelectArr" :key="index" :value="item.key">
                        {{item.val}}
                      </a-select-option>
                    </a-select>
                  </a-col>
                  <a-col :span="6">
                    <a-date-picker @change="UnusualOnChange" />
                  </a-col>

                  <a-col :span="3">
                    <a-button type="primary" @click="searchBtnClkFn">查询</a-button>
                  </a-col>
                </a-row>
              </a-col>

              <a-col :span="3" v-if="radioCurrentIdx != 'g'">
                <a-button type="primary" @click="searchBtnClkFn">查询</a-button>
              </a-col>

            </a-row>
          </a-input-group>
        </a-col>

        <a-col :span="24" class="mtb_10">
          <a-space>
            <a-button type="primary" v-if="radioCurrentIdx == 'b'" @click="batchImportBtnClk">批量导入</a-button>
            <a-button type="primary">批量导出</a-button>
            <a-select default-value="批量操作" style="width: 120px" @change="batchHandleChange" v-if="radioCurrentIdx == 'c'">
              <a-select-option value="1">
                入职
              </a-select-option>
              <a-select-option value="2" disabled>
                离职
              </a-select-option>
              <a-select-option value="3">
                取消入职
              </a-select-option>
            </a-select>
          </a-space>
        </a-col>
      </a-row>
    </div>

    <!-- table -->
    <div class="table">
      <advance-table :columns="columns" :data-source="tableData" title=" " :loading="loading" :row-selection="rowSelection" rowKey="id" @search="onSearch" @refresh="onRefresh" :format-conditions="true" @reset="onReset" :pagination="{
        current: page,
        pageSize: pageSize,
        total: total,
        showSizeChanger: true,
        showLessItems: true,
        showQuickJumper: true,
        showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，总计 ${total} 条`,
        onChange: onPageChange,
        onShowSizeChange: onSizeChange,
      }">
        <template slot="project" slot-scope="text">
          {{text.text.name}}
        </template>
        <template slot="status" slot-scope="text">
          {{text.text | statusFilter}}
        </template>
        <template slot="createTime" slot-scope="text">
          {{text.text | dateFormatFilter}}
        </template>
        <template slot="entryTime" slot-scope="text">
          {{text.text | dateFormatFilter}}
        </template>
        <template slot="updateTime" slot-scope="text">
          {{text.text | dateFormatFilter}}
        </template>
        <template slot="setting" slot-scope="text">
          <a @click="goDetails(text.record.id)">详情</a>
          <a-divider type="vertical" />
          <a @click="entryJobClkFn(text.record.id)">入职</a>
          <a-divider type="vertical" />
          <a @click="cancelEntryJobClkFn(text.record.id)">取消入职</a>
          <a-divider type="vertical" />
          <a @click="quitPOsitionClkFn(text)">离职</a>
        </template>
        <template slot="contract" slot-scope="text">
          {{text.text.signStartTime | dateFormatFilter}}
        </template>
        <template slot="setting1" slot-scope="text">
          <a @click="cancelEntryClkFn(text.record.id)">取消入职</a>
          <a-divider type="vertical" />
          <a @click="entryAgainClkFn(text.record.id)">再次入职</a>
        </template>
      </advance-table>
    </div>

    <!-- 离职modal -->
    <a-modal title="离职办理" centered :visible="modalShow" :confirm-loading="confirmLoading" @ok="leaveModalHandleOk" @cancel="leaveModalHandleCancel">
      <a-form-model :model="leaveModalForm" :label-col="labelCol" :wrapper-col="wrapperCol" :rules="modalRules" ref="leaveModalForm">
        <a-form-model-item label="离职员工">
          <span style="color: #BFBFBF;">{{leaveModalForm.name}}</span>
        </a-form-model-item>

        <a-form-model-item label="离职原因" prop="dimissionReason">
          <a-select show-search allowClear placeholder="请选择离职原因" v-model="leaveModalForm.dimissionReason" option-filter-prop="children" :style="setWidth" :filter-option="filterOption" @focus="handleFocusModal" @blur="handleBlurModal" @change="leaveModalSelectOnchange">
            <a-select-option v-for="(item, index) in leaveModalReasonData" :key="index" :value="item">
              {{item}}
            </a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item label="离职日期" prop="dimissionDate">
          <a-date-picker @change="dimissionOnchange" v-model="leaveModalForm.dimissionDate" placeholder="请选择离职日期" :style="setWidth" :disabled-date="disabledDate" format="YYYY-MM-DD" />
        </a-form-model-item>

        <a-form-model-item label="社保停缴月份" prop="socialSecurityStopDate">
          <a-month-picker @change="socialSecurityStopDateOnchange" v-model="leaveModalForm.socialSecurityStopDate" placeholder="请选择社保停缴月份" format="YYYY-MM" :style="setWidth" />
        </a-form-model-item>

        <a-form-model-item label="公积金停缴月份" prop="accumulationFundStopDate">
          <a-month-picker @change="stopFundDateStopDateOnchange" v-model="leaveModalForm.accumulationFundStopDate" placeholder="请选择公积金停缴月份" format="YYYY-MM" :style="setWidth" />
        </a-form-model-item>

        <a-form-model-item label="内容描述" class="wordStatistics_wrapper">
          <a-textarea style="width: 220px;" placeholder="请输入内容" :maxLength="300" :auto-size="{ minRows: 2, maxRows: 6 }" v-model="leaveModalForm.cntDescVal" />
          <span class="wordStatistics">{{leaveModalForm.cntDescVal.length}}/300</span>
        </a-form-model-item>

        <a-col :span="7"></a-col>

        <a-checkbox @change="onChange" style="opacity: 0">
          是否发送离职协议
        </a-checkbox>
      </a-form-model>
    </a-modal>
  </a-card>
</template>

<script>
import AdvanceTable from '@/components/table/advance/AdvanceTable'
import { employeeManageListApi, entryByPitchApi, batchCancelEntryApi, projectGetListApi, employeeDimissionApi } from '@/services/employeeManage'
import datas from "@/utils/data"
import { transferDate } from '@/utils/util'
import moment from 'moment'

let ids = [] // 批量入职、取消入职传参

// 列复选框
const rowSelection = {
  onChange: (selectedRowKeys, selectedRows) => {
    console.log(
      `selectedRowKeys: ${selectedRowKeys}`,
      "selectedRows: ",
      selectedRows
    );

    ids = selectedRowKeys.toString()
  },
  onSelect: (record, selected, selectedRows) => {
    console.log(record, selected, selectedRows);
  },
  onSelectAll: (selected, selectedRows, changeRows) => {
    console.log(selected, selectedRows, changeRows);
  },
};

const statusArr = ['', 'Supplement', 'UnEntry', 'OnJob', 'UnDimission', 'Expired']
// Supplement/待完善资料,UnEntry/待入职,OnJob/在职,UnDimission/待离职,Dimission/已离职(废弃)，Expired/已失效 

const letterToIndex = [
  {
    letter: 'a',
    index: 0
  },
  {
    letter: 'b',
    index: 1
  },
  {
    letter: 'c',
    index: 2
  },
  {
    letter: 'd',
    index: 3
  },
  {
    letter: 'e',
    index: 4
  },
  {
    letter: 'f',
    index: 5
  },
  {
    letter: 'g',
    index: 6
  }
]



export default {
  name: "employeeManagement",
  components: { AdvanceTable },
  filters: {
    statusFilter (str) {
      switch (str) {
        case 'Supplement':
          return '待补充'
        case 'UnEntry':
          return '待入职'
        case 'OnJob':
          return '在职'
        case 'UnDimission':
          return '待离职'
        case 'Dimission':
          return '已离职'
        case 'Expired':
          return '已失效'
      }
    },
    dateFormatFilter (val) {
      if (val) {
        return transferDate(val, 0)
      } else {
        return ''
      }

    }

  },
  data () {
    return {
      defaultSpan: 12,
      defaultSpanItem: 8,
      radioValue: 'a',
      loading: false,
      page: 1,
      total: 0,
      pageNum: 1,
      pageSize: 10,
      columns: datas.columns,
      dataSource: [],
      conditions: {},
      btnName: '批量导出',
      radioCurrentIdx: 'a',
      searchForm: {
        nameTeldepartmentVal: '',
        corpProNameVal: '',
      },
      tableData: [], // 全部      
      rowSelection,
      modalShow: false,
      confirmLoading: false,
      labelCol: { span: 7 },
      wrapperCol: { span: 12 },
      leaveModalForm: {
        id: '',
        userId: null,
        name: '',
        dimissionReason: undefined,
        dimissionDate: moment(moment(), 'YYYY-MM-DD'),
        // dimissionDate: moment(moment().subtract(1, "days"), 'YYYY-MM-DD'),
        socialSecurityStopDate: undefined,
        accumulationFundStopDate: undefined,
        cntDescVal: '',
      },
      setWidth: 'width: 220px',
      modalRules: {
        dimissionReason: [
          { required: true, message: '请选择离职原因', trigger: 'blur' },
        ],
        dimissionDate: [
          { required: true, message: '请选择离职日期', trigger: 'change' },
        ],
        socialSecurityStopDate: [
          { required: true, message: '请选择社保停缴月份', trigger: 'change' },
        ],
        accumulationFundStopDate: [
          { required: true, message: '请选择公积金停缴月份', trigger: 'change' },
        ],
      },
      employeeManagementTabArr: datas.employeeManagementTabArr,
      selectData: [],
      keyword: null,
      projectId: null,
      status: null,
      contractStatus: null,
      contractSignStartTime: null,
      typeSelectArr: datas.typeSelectArr,
      leaveModalReasonData: datas.leaveModalReasonData,
      isUnusual: null,
    };
  },
  created () {
    this.getData()
    this.projectGetList()
  },
  methods: {
    moment,

    disabledDate (current) {
      return current > moment().endOf('day');
    },

    batchImportBtnClk () {
      this.$router.push({ path: '/quickEntry/batchProcessing' })
    },

    projectGetList () {
      projectGetListApi().then(res => {
        let { code, data } = res.data

        if (code === 200) {
          this.selectData = data
        }
      })
    },

    getData () {
      this.loading = true
      let { keyword, projectId, status, pageNum, pageSize, contractStatus, contractSignStartTime, isUnusual } = this
      let params = {
        keyword,
        projectId,
        status,
        pageNum,
        pageSize,
        contractStatus,
        isUnusual,
        contractSignStartTime
      }

      /**
       * contractStatus: 合同类型
       * contractSignStartTime: 人员异动-选择日期
       * isUnusual: 是否异动 1 是
       */

      employeeManageListApi(params).then(res => {
        let { code, data } = res.data
        if (code == 200) {
          this.tableData = data.content
          this.page = data.pageNum
          this.total = data.totalPages
          this.pageSize = data.pageSize
          this.loading = false
        }
      })
    },

    radioOnChange (e) {
      this.radioCurrentIdx = e.target.value;

      letterToIndex.forEach(item => {
        if (item.letter == this.radioCurrentIdx) {
          this.status = statusArr[item.index] ? statusArr[item.index] : null
        }
      })

      if (e.target.value == 'g') {
        this.isUnusual = 1,
          this.defaultSpan = 24,
          this.defaultSpanItem = 4
        this.columns = datas.columns1 // 切换人员异动表头
      } else {
        this.isUnusual = undefined
        this.contractStatus = undefined
        this.contractSignStartTime = undefined
        this.columns = datas.columns
      }
      this.getData()
    },

    onChange (date, dateString) {
      console.log(date, dateString);
    },

    handleChange1 (value) {
      console.log(`selected ${value}`);
      this.searchForm.corpProNameVal = value
    },

    UnusualHandleChange (value) {
      this.contractStatus = value
    },
    leaveModalSelectOnchange (value) {
      this.leaveModalForm.dimissionReason = value
    },
    handleBlur () {
      console.log('blur');
    },

    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },

    onSearch (conditions, searchOptions) {
      console.log(searchOptions)
      this.page = 1
      this.conditions = conditions
      this.getData()
    },
    onSizeChange (current, size) {
      this.page = 1
      this.pageSize = size
      this.getData()
    },
    onRefresh (conditions) {
      this.conditions = conditions
      this.getData()
    },
    onReset (conditions) {
      this.conditions = conditions
      this.getData()
    },
    onPageChange (page, pageSize) {
      this.page = page
      this.pageSize = pageSize
      this.getData()
    },

    // 查询
    searchBtnClkFn () {
      let { searchForm } = this
      this.keyword = searchForm.nameTeldepartmentVal
      this.projectId = searchForm.corpProNameVal
      this.getData()
    },

    goDetails (id) {
      this.$router.push(`/quickEntry/employeeDetails?id=${id}`)
    },

    quitPOsitionClkFn (data) {
      this.leaveModalForm = { ...this.leaveModalForm, ...data.record }
      this.modalShow = true
      this.$nextTick(() => {
        this.$refs['leaveModalForm'].clearValidate();
        this.$refs['leaveModalForm'].resetFields();
        this.leaveModalForm.cntDescVal = ''
      })


    },

    leaveModalHandleOk () {
      let { id, userId, cntDescVal, dimissionDate, dimissionReason, accumulationFundStopDate, socialSecurityStopDate } = this.leaveModalForm

      let params = {
        userId: id,// 用户ID
        employeeId: userId,// 雇员ID
        reason: dimissionReason,// 离职原因
        dimissionDateStr: dimissionDate,// 离职日期
        stopSocialDateStr: socialSecurityStopDate + '-01',// 停缴社保日期
        stopFundDateStr: accumulationFundStopDate + '-01',// 停缴公积金日期
        memo: cntDescVal,// 内容描述
        sendAgreement: false// 是否发送离职协议
      }

      this.$refs.leaveModalForm.validate(valid => {
        if (valid) {
          this.confirmLoading = true;
          employeeDimissionApi(params).then(res => {
            this.modalShow = false;
            this.confirmLoading = false;

            let { code, msg } = res.data
            if (code === 200) {
              this.$message.success(msg);
            } else if (code === 400) {
              this.$message.error(msg);
            } else {
              console.log(msg)
            }

          })
        } else {
          // console.log('error submit!!');
          return false;
        }
      });


    },

    leaveModalHandleCancel () {
      this.modalShow = false;
    },

    handleBlurModal () {
      console.log('blur');
    },
    handleFocus () {
      console.log('focus');
    },
    handleFocusModal () {
      console.log('focus');
    },
    filterOption1 (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },

    dimissionOnchange (date, dateString) {
      console.log(date, dateString)
      this.leaveModalForm.dimissionDate = dateString
      if (!dateString) {
        this.leaveModalForm.dimissionDate = undefined
      }
    },

    socialSecurityStopDateOnchange (date, dateString) {
      console.log(date, dateString)
      this.leaveModalForm.socialSecurityStopDate = dateString
      if (!dateString) {
        this.leaveModalForm.socialSecurityStopDate = undefined
      }
    },

    stopFundDateStopDateOnchange (date, dateString) {
      console.log(date, dateString)
      this.leaveModalForm.accumulationFundStopDate = dateString
      if (!dateString) {
        this.leaveModalForm.accumulationFundStopDate = undefined
      }
    },

    batchHandleChange (value) {
      console.log(ids)
      if (ids.length == 0) {
        this.$message.error('请勾选要操作的项目');
        return
      }

      if (Number(value) === 1) { // 入职
        let params = {
          ids
        }
        this.entryJobPackApi(params, 'batch')
      } else { // 取消入职
        let params = {
          ids
        }

        this.leaveJobPackApi(params, 'batch')
      }
    },

    // 入职接口
    entryJobPackApi (params, type) {
      entryByPitchApi(params).then(res => {
        if (res.data.code === 200) {
          this.$message.success(type == 'batch' ? '批量入职成功' : '入职成功');
        } else {
          this.$message.error(type == 'batch' ? '批量入职失败' : '入职失败');
        }
      })
    },

    // 取消入职接口
    leaveJobPackApi (params, type) {
      batchCancelEntryApi(params).then(res => {
        if (res.data.code === 200) {
          this.$message.success(type == 'batch' ? '批量取消入职成功' : '取消入职成功');
        } else {
          this.$message.error(type == 'batch' ? '批量取消入职失败' : '取消入职失败');
        }
      })
    },

    // 单行入职
    entryJobClkFn (id) {
      let params = {
        ids: id
      }

      this.entryJobPackApi(params, 'single')
    },

    // 单行取消入职
    cancelEntryJobClkFn (id) {
      let params = {
        ids: id
      }

      this.leaveJobPackApi(params, 'single')
    },

    UnusualOnChange (date, dateString) {
      console.log(date, dateString)
      this.contractSignStartTime = dateString
    },

    cancelEntryClkFn (id) {
      let params = {
        ids: id
      }

      this.leaveJobPackApi(params, 'single')
    },

    entryAgainClkFn (id) {
      let params = {
        ids: id
      }

      this.entryJobPackApi(params, 'single')
    },


  },

};
</script>

<style scoped lang="less">
.mtb_10 {
  margin: 20px 0;
}

.pl_50 {
  padding-left: 50px;
}

.radioGroup_div {
  align-items: center;
  margin-bottom: 20px;
}

.dsp_flex {
  display: flex;
  display: -webkit-flex;
}

.wordStatistics_wrapper {
  position: relative;
}

.wordStatistics {
  position: absolute;
  bottom: -30px;
  right: 0;
  line-height: 1;
}
</style>
